package com.ruoyi.web.controller.workJob;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.workFlow.service.OperationalWorkFlowService;
import com.ruoyi.worker.domain.*;
import com.ruoyi.worker.service.AttendanceGroupService;
import com.ruoyi.worker.service.CompanyService;
import com.ruoyi.worker.service.TimeShiftService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/workJobApi/attendance")
public class AttendanceGroupController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(AttendanceGroupController.class);
    @Autowired
    private AttendanceGroupService attendanceGroupService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private TimeShiftService timeShiftService;
    @Resource
    private OperationalWorkFlowService operationalWorkFlowService;

    /**
     * 获取考勤信息列表
     */
   // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:list')")
    @GetMapping("/listAttendanceInfo")
    public TableDataInfo listAttendanceInfo(AttendanceInfo attendanceInfo)
    {
        startPage();
        List<AttendanceInfo> list = attendanceGroupService.listAttendanceInfo(attendanceInfo);
        return getDataTable(list);
    }

    /**
     * @description:  根据id获取临时工考勤汇总记录
     * @author 刘松山
     * @date 2021/12/24 13:33
     *
     */
    @GetMapping(value = { "/getAttendanceStatistics/{id}"})
    public AjaxResult getAttendanceStatistics(@PathVariable(value = "id", required = false) Long id)
    {
        AjaxResult ajax = AjaxResult.success();

        AttendanceInfo info = new AttendanceInfo();
        info.setId(id);

        ajax.put(AjaxResult.DATA_TAG, attendanceGroupService.getAttendanceStatistics(info));


        return ajax;
    }
    /**
     * 根据id获取详细信息
     */
    //@PreAuthorize("@ss.hasPermi('job:attendanceGroup:query')")
    @GetMapping(value = { "/", "/{id}" })
    public AjaxResult getInfo(@PathVariable(value = "id", required = false) Long id)
    {
        AjaxResult ajax = AjaxResult.success();

        Company company = new Company();
        company.setStatus(1);
        ajax.put("companys",companyService.getCompanyList(company));
        SysPost post =new  SysPost();
        post.setStatus("0");
        ajax.put("sysPost",postService.selectPostList(post));
        TimeShift timeShift = new TimeShift();
        timeShift.setStatus(1);
        ajax.put("timeShift",timeShiftService.getTimeShiftList(timeShift));
        if (StringUtils.isNotNull(id))
        {
            ajax.put(AjaxResult.DATA_TAG, attendanceGroupService.getAttendanceGroup(id) );

        }
        return ajax;
    }
    /**
     * 新增
     */
  //  @PreAuthorize("@ss.hasPermi('workJobApi:attendance:add')")
    @Log(title = "新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody AttendanceGroup attendanceGroup)
    {

        attendanceGroup.setCreateBy(getUsername());
        return toAjax(attendanceGroupService.addAttendanceGroup(attendanceGroup));
    }

    /**
     * 修改
     */
   // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:edit')")
    @Log(title = "修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody AttendanceGroup attendanceGroup)
    {
//        if(attendanceGroup.getAttendanceFlag() !=null){
//            AttendanceGroup a =attendanceGroupService.getAttendanceGroup(attendanceGroup.getId());
//            if(null==attendanceGroup.getGroupName() || null==attendanceGroup.getCompanyName()){
//                if(attendanceGroup.getAttendanceFlag()==2){
//                    return AjaxResult.error(attendanceGroup.getWorkerName()+"的数据缺失，不能修改考勤状态为正常");
//                }
//
//            }
//        }

        attendanceGroup.setUpdateBy(getUsername());
        return toAjax(attendanceGroupService.updateAttendanceGroup(attendanceGroup));
    }

    /**
     * 删除
     */
    //@PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:delete')")
    @Log(title = "删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(attendanceGroupService.deleteAttendanceGroupIds(ids));
    }

    /**
     * 状态考勤汇总记录的确认修改
     */
   // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:confirm')")
    @GetMapping(value = { "/modifyAttendanceInfo/{id}" })
    public AjaxResult modifyAttendanceInfo(@PathVariable(value = "id", required = true) Long id)
    {
        AttendanceInfo info = new AttendanceInfo();
        info.setId(id);
        AttendanceInfo a =attendanceGroupService.getAttendanceStatistics(info);
        int  flag = attendanceGroupService.countAttendanceSum(a);
          if(flag >0){
              return AjaxResult.error("需求用单号为：" + a.getOrderCode() + "中存在考勤状态为未知情况，请核对！");
          }

         AttendanceInfo attendanceInfo = new AttendanceInfo();
         attendanceInfo.setStatus(3);
         attendanceInfo.setId(id);
        return toAjax(attendanceGroupService.modifyAttendanceInfo(attendanceInfo));
    }
    /**
     *  修改员工考勤状态
     */

    @GetMapping(value = { "/changAttendanceStatus/{id}/{attendanceFlag}" })
    public AjaxResult changAttendanceStatus(@PathVariable(value = "id", required = true) Long id,
                                            @PathVariable(value = "attendanceFlag", required = true) Integer attendanceFlag)
    {

          return toAjax(attendanceGroupService.changAttendanceStatus(id,attendanceFlag));
    }

    /**
     * 导出员工考勤
     *
     * @param attendanceGroup
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author 刘松山
     * @date 2021/9/10 19:28
     */
   // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:export')")
    @GetMapping("/attendanceExport")
    public AjaxResult attendanceExport(AttendanceGroup attendanceGroup) {
        List<AttendanceGroup> orderList = attendanceGroupService.listAttendanceGroup(attendanceGroup);
        if (orderList.isEmpty()) {
            return AjaxResult.error("需要导出的数据为空");
        }

        ExcelUtil<AttendanceGroup> util = new ExcelUtil<AttendanceGroup>(AttendanceGroup.class);
        return util.exportExcel(orderList, "员工考勤数据");


    }

    /**
     * @param file
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 班组考勤信息导入
     * @Author : leizhang
     * @Date 5:12 下午 2021/9/5
     **/
   // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:import')")
    @PostMapping("/importDataGroup")
    public AjaxResult importDataGroup(MultipartFile file) {
        List<ExcelToolDomain> ExcelToolDomains = null;
        try {
            ExcelToolDomains = baseImport(file.getInputStream(), 1, 1, false, ExcelToolDomain.class);
        } catch (Exception e) {
            LOGGER.error("班组信息导入失败:[{}]", e.getMessage(), e);
        }
        if (null == ExcelToolDomains) {
            return AjaxResult.error("excel班组信息导入失败，信息为空");
        }

        AjaxResult a = attendanceGroupService.importExcel(ExcelToolDomains);

        return a;
    }



    /**
     * @param excelToolDomains
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 员工考勤详细
     * @Author : leizhang
     * @Date 6:33 下午 2021/9/5
     **/
    //@GetMapping("/getAttendance")
    public TableDataInfo getAttendance(ExcelToolDomain excelToolDomains) {
        startPage();
        List<ExcelToolDomain> workerInfo = attendanceGroupService.getAttendanceInfos(excelToolDomains);
        return getDataTable(workerInfo);
    }
    /**
     * @param excelToolDomains
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 员工考勤详细
     * @Author : leizhang
     * @Date 6:33 下午 2021/9/5
     **/
   // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:list')")
    @GetMapping("/getAttendanceSum")
    public TableDataInfo getAttendanceSum(ExcelToolDomain excelToolDomains) {
        startPage();
        List<ExcelToolDomain> list = attendanceGroupService.getAttendanceSum(excelToolDomains);
        return getDataTable(list);
    }

    @GetMapping("/getImgList")
    public TableDataInfo getImgList(AttendanceStatisticsImg a) {
        startPage();

        List<AttendanceStatisticsImg> list = attendanceGroupService.getAttendanceStatisticsImg(a);
        return getDataTable(list);
    }

    @Log(title = "删除上传凭证", businessType = BusinessType.DELETE)
    @GetMapping("/delImg")
    public AjaxResult remove(AttendanceStatisticsImg a)
    {
        return toAjax(attendanceGroupService.delAttendanceStatisticsImg(a));
    }


    /**
     * @param requestParam
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @Description : 启动临时工审核流程
     * @Author : leizhang
     * @Date 2:27 下午 2021/11/4
     **/
    @PostMapping("/startAuditWorkFlow")
    public AjaxResult startAuditWorkFlow(@RequestBody Map<String, Object> requestParam) {
        try {
            operationalWorkFlowService.startOperationalWorkFlowProcess(requestParam);
            return AjaxResult.success();
        } catch (Exception e) {
            LOGGER.error("临时工确认审核流程启动失败:{}", e.getCause(), e);
            return AjaxResult.error();
        }
    }




    private <T> List<T> baseImport(InputStream inputStream, Integer titleRows, Integer headerRows,
                                   boolean needVerify, Class<T> pojoClass) throws Exception {
        if (inputStream == null) {
            return null;
        } else {
            final ImportParams params = new ImportParams();
            params.setTitleRows(titleRows);
            params.setHeadRows(headerRows);
            params.setNeedVerify(true);
            params.setNeedSave(false);
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        }

    }
}
